import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
// import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import { asyncRouterMap } from '@/config/router'
let asyncRouterFlag = 0
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const allowList = ['login', 'register', 'registerResult', '/user/login'] // no redirect allowList
const loginRoutePath = '/user/login'
const defaultRoutePath = '/dashboard/workplace'

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`))
  /* has token */
  if (storage.get(ACCESS_TOKEN)) {
    if (to.path === loginRoutePath) {
        next({ path: defaultRoutePath })
        NProgress.done()
    } else {
      if (store.getters.userInfo) {
        // 添加flag防止多次获取动态路由和栈溢出
        if (!asyncRouterFlag && store.getters.addRouters.length === 0) {
          asyncRouterFlag++
          store.dispatch('GenerateRouters', asyncRouterMap)
          const asyncRouters = store.getters.addRouters
          router.addRoutes(asyncRouters)
          next({ ...to, replace: true })
        } else {
          next()
        }
      }
      next()
      NProgress.done()
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
